<?php

namespace app\common\model\xiservice;

use think\Model;
use addons\xiservice\controller\WeixinMini;
use app\common\model\xiservice\Address;
use app\common\model\xiservice\Area;
use app\common\model\xiservice\Service;
use app\common\model\xiservice\Benfit as BenfitModel;
use app\common\model\xiservice\User as XiserviceUser;
use app\common\model\xiservice\Comment as CommentModel;
use app\common\model\xiservice\Schedule as ScheduleModel;
use traits\model\SoftDelete;
use think\Exception;
use think\Db;

class Order extends Model
{

    use SoftDelete;


    // 表名
    protected $name = 'xiservice_order';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [
        'chose_type_text',
        'service_money',
        'visit_pay_status_text',
        'bargain_text',
        'service_start_time_text',
        'pay_type_text',
        'pay_status_text',
        'pay_time_text',
        'confirm_time_text',
        'service_time_text',
        'comment_time_text',
        'cancel_time_text',
        'refund_time_text',
        'order_status_text',
        'province_text',
        'city_text',
        'area_text',
        'notify_text',
        'is_today',
        'createtime_text',
        'createtime_mission',
        'service_desc_images_arr',
        'service_check_images_arr',
        'check_time_text',
        'check_status_text',
    ];

    public function getgenhuanlist(){
        $res = Db::name('xiservice_user')->where('group_id',2)->select();
        return $res;
    }
    public function getPayTypeList()
    {
        return ['1' => __('微信支付')];
    }

    public function getPayStatusList()
    {
        return ['10' => __('未支付'), '20' => __('已支付')];
    }

    public function getChoseTypeList()
    {
        return ['0' => __('Chose_type 0'), '1' => __('Chose_type 1')];
    }

    public function getVisitPayStatusList()
    {
        return ['0' => __('Visit_pay_status 0'), '1' => __('Visit_pay_status 1')];
    }

    public function getOrderStatusList()
    {
        return [
            '0' => __('已取消'), '10' => __('待支付'),
            '20' => __('待确认'), '21' => __('已拒单'),
            '30' => __('待服务'), '40' => __('服务中'),
            '50' => __('已完成'), '60' => __('已退款'),
            '70' => __('等待验收')
        ];
    }

    public function getBargainList()
    {
        return ['0' => __('Bargain 0'), '1' => __('Bargain 1')];
    }

    public function getNotifyList()
    {
        return ['0' => __('Notify 0'), '1' => __('Notify 1')];
    }

    public function getCheckStatusList()
    {
        return [
            '10' => __('待完工'),'20' => __('确认中'),
            '30' => __('验收合格'), '40' => __('验收不合格'),
        ];
    }

    public function getPayTypeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['pay_type']) ? $data['pay_type'] : '');
        $list = $this->getPayTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function getIsTodayAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['service_start_time']) ? $data['service_start_time'] : '');
        if (!$value) {
            return 0;
        }
        $today = date("Y-m-d", time());
        $reserve = date("Y-m-d", $value);
        if ($today == $reserve) {
            return 1;
        } else {
            return 0;
        }
    }

    public function getOrderStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['order_status']) ? $data['order_status'] : '');
        $list = $this->getOrderStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function getPayStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['pay_status']) ? $data['pay_status'] : '');
        $list = $this->getPayStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getChoseTypeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['chose_type']) ? $data['chose_type'] : '');
        $list = $this->getChoseTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getVisitPayStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['visit_pay_status']) ? $data['visit_pay_status'] : '');
        $list = $this->getVisitPayStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getBargainTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['bargain']) ? $data['bargain'] : '');
        $list = $this->getBargainList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function getCreatetimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['createtime']) ? $data['createtime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    public function getCreatetimeMissionAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['createtime']) ? $data['createtime'] : '');
        return is_numeric($value) ? date("m-d H:i", $value) : $value;
    }


    public function getServiceStartTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['service_start_time']) ? $data['service_start_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getPayTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['pay_time']) ? $data['pay_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getConfirmTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['confirm_time']) ? $data['confirm_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getServiceTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['service_time']) ? $data['service_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getCommentTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['comment_time']) ? $data['comment_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getCancelTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['cancel_time']) ? $data['cancel_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getRefundTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['refund_time']) ? $data['refund_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getNotifyTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['notify']) ? $data['notify'] : '');
        $list = $this->getNotifyList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function getServiceMoneyAttr($value, $data)
    {
        $total_money = isset($data['total_money']) ? $data['total_money'] : 0;
        $visit_money = isset($data['visit_money']) ? $data['visit_money'] : 0;
        $res = bcsub($total_money, $visit_money, 2);
        if ($res <= 0) {
            $res = 0;
        }
        return $res;
    }

    protected function setServiceStartTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setPayTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setConfirmTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setServiceTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setCommentTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setCancelTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setRefundTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }


    public function getProvinceTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['province_id']) ? $data['province_id'] : 0);
        $province = Area::where('id', $value)->find();
        return $province ? $province['name'] : '';
    }

    public function getCityTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['city_id']) ? $data['city_id'] : 0);
        $city = Area::where('id', $value)->find();
        return $city ? $city['name'] : '';
    }

    public function getAreaTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['area_id']) ? $data['area_id'] : 0);
        $area = Area::where('id', $value)->find();
        return $area ? $area['name'] : '';
    }

    public function getServiceDescImagesArrAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['service_desc_images']) ? $data['service_desc_images'] : '');
        $array = [];
        if ($value) {
            $list = explode(',', $value);
            for ($i = 0; $i < count($list); $i++) {
                array_push($array, cdnurl($list[$i], true));
            }
        }
        return $array;
    }

    public function getServiceCheckImagesArrAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['service_check_images']) ? $data['service_check_images'] : '');
        $array = [];
        if ($value) {
            $list = explode(',', $value);
            for ($i = 0; $i < count($list); $i++) {
                array_push($array, cdnurl($list[$i], true));
            }
        }
        return $array;
    }

    public function getCheckTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['check_time']) ? $data['check_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    public function getCheckStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['check_status']) ? $data['check_status'] : '');
        $list = $this->getCheckStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function member()
    {
        return $this->belongsTo('app\common\model\User', 'user_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }


    public function user()
    {
        return $this->belongsTo('app\common\model\xiservice\User', 'user_id', 'user_id', [], 'LEFT')->setEagerlyType(0);
    }

    public function worker()
    {
        return $this->belongsTo('app\common\model\xiservice\User', 'worker_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function service()
    {
        return $this->belongsTo('app\common\model\xiservice\Service', 'service_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    //展示下单情况
    public function orderShow($userId, $addressId, $serviceId, $couponId, $servicenums = 1, $workerId = 0)
    {

        if ($servicenums == 0) {
            $servicenums = 1;
        }
        $service = Service::where('id', $serviceId)->find();
        if (!$service) {
            return ["status" => false, "data" => [], "msg" => "服务信息错误!"];
        }
        if ($addressId == 0) {
            $address = Address::where('user_id', $userId)->where('is_default', 1)->find();
        } else {
            $address = Address::where('id', $addressId)->where('user_id', $userId)->find();
            if (!$address) {
                return ["status" => false, "data" => [], "msg" => "地址信息错误!"];
            }
        }
        //地址信息
        $provinceId = 0;
        $province = '';
        $cityId = 0;
        $city = '';
        $areaId = 0;
        $area = '';
        $addr = '';
        $addrDetail = '';
        $lat = '';
        $lng = '';
        $name = '';
        $phone = '';
        if ($address) {
            $addressId = $address['id'];
            $provinceId = $address['province_id'];
            $province = $address['province_text'];
            $cityId = $address['city_id'];
            $city = $address['city_text'];
            $areaId = $address['area_id'];
            $area = $address['area_text'];
            $addr = $address['addr'];
            $addrDetail = $address['addr_detail'];
            $lat = $address['lat'];
            $lng = $address['lng'];
            $name = $address['name'];
            $phone = $address['phone'];
        }

        $scale = 1;
        if ($workerId) {
            $worker = XiserviceUser::where('user_id', $workerId)->find();
            if ($worker) {
                if ($worker['level'] == 1) {
                    isset(config('xiservice.level')['level_one_scale']) ? $scaleConfig = config('xiservice.level')['level_one_scale'] : $scaleConfig = 100;
                } else if ($worker['level'] == 2) {
                    isset(config('xiservice.level')['level_two_scale']) ? $scaleConfig = config('xiservice.level')['level_two_scale'] : $scaleConfig = 100;
                } else {
                    isset(config('xiservice.level')['level_three_scale']) ? $scaleConfig = config('xiservice.level')['level_three_scale'] : $scaleConfig = 100;
                }
                if ($scaleConfig) {
                    $scale = $scaleConfig / 100;
                }
            }
        }
        //计算不同等级服务人员的价格
        $saleprice = bcmul($service['saleprice'], $scale, 2);

        //服务时长
        $service_duration = 30;

        if ($service['service_time_type'] == 2) {
            //自选时长
            $service_duration = $service['service_time_unit'] * $servicenums;
        } else if ($service['service_time_type'] == 1) {
            //固定时长
            $service_duration = $service['service_duration'];
        } else {
            //无时长
            $service_duration = 30;
        }
        if ($service['bargain'] == 0) {
            //固定价格情况下

            $total_money = bcadd($service['serviceprice'], $saleprice, 2);
            $pay_money = bcadd($service['serviceprice'], $saleprice, 2);
        } else {
            //非固定价格情况下
            $total_money = 0;
            $pay_money = 0;
        }
        //优惠券信息
        $can_coupons = [];
        $coupon = [];
        $coupon_money = 0;

        $data = [
            "chose_type" => $service['is_chose'],
            "user_id" => $userId,
            "worker_id" => $workerId,
            "service_id" => $serviceId,
            "service" => $service,
            "servicenums" => $servicenums,
            "saleprice" => $saleprice,
            "total_money" => $total_money,
            "pay_money" => $pay_money,
            "visit_money" => $service['serviceprice'],
            "bargain" => $service['bargain'],
            "service_duration" => $service_duration,
            "province_id" => $provinceId,
            "province_text" => $province,
            "city_id" => $cityId,
            "city_text" => $city,
            "area_id" => $areaId,
            "area_text" => $area,
            "addr" => $addr,
            "addr_detail" => $addrDetail,
            "name" => $name,
            "phone" => $phone,
            "lat" => $lat,
            "lng" => $lng,
            'can_coupons' => $can_coupons,
            "coupon" => $coupon,
            "coupon_id" => $couponId,
            "coupon_money" => $coupon_money,
            "address_id" => $addressId
        ];

        //分类是否有合同
        $data['have_contract'] = Db::name('xiservice_contract')
            ->where('service_id', $serviceId)
            ->count();

        return ["status" => true, "data" => $data, "msg" => "查询成功"];
    }

    //创建订单
    public function createorder($data, $uid)
    {


        Db::startTrans();
        $orderNo = 'JZ' . date("YmdHis") . mt_rand(1000, 9999) . $uid;
        try {
            $data['user_id'] = $uid;
            $data['order_no'] = $orderNo;
            $res = $this->allowField(true)->save($data);
            //更新服务信息
            $service = Service::where('id', $data['service_id'])->setInc('salenums');
            //更新服务人员时间表
            if ($data['worker_id']) {
                $scheduleModel = new \app\common\model\xiservice\Schedule;
                $req = $scheduleModel->orderSchedule($data['worker_id'], $this->id, $data['service_start_time'], $data['service_duration']);
            }

            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            return ["status" => false, "data" => [], "msg" => $e->getMessage()];
        }

        $res = $this->where('order_no', $orderNo)->find();
        return ["status" => true, "data" => $res['id'], "msg" => "创建订单成功"];
    }

    //$checkinfo       订单状态：  0=全部，1=待确认，2=待服务，3=服务中，4=已完成，5=取消/退款，7=质保中
    public function getCheckinfoStatus($checkinfo)
    {
        $where = [];
        switch ($checkinfo) {
            case 1:
                $where['order_status'] = 20;
                break;
            case 2:
                $where['order_status'] = 30;
                break;
            case 3:
                $where['order_status'] = 40;
                break;
            case 4:
                $where['order_status'] = 50;
                break;
            case 5:
                $where['order_status'] = ['in', '0,60'];
                break;
            case 7:
                $where['order_status'] = 70;
                break;
            case 8:
                $where['order_status'] = ['in', '20,50'];
                break;    
            default:
                $where['order_status'] = ['in', '0,10,20,30,40,50,60'];
                break;
        }
        return $where;
    }

    //worker      订单状态：  0=全部，1=待接单，2=今日服务，3=待服务，4=服务中，5=已完成，6=质保中
    public function getWorkerCheckinfoStatus($checkinfo)
    {
        $where = [];
        $beginToday = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
        $endToday = mktime(0, 0, 0, date('m'), date('d') + 1, date('Y')) - 1;
        switch ($checkinfo) {
            case 1:
                $where['order_status'] = 20;
                break;
            case 2:
                $where['service_start_time'] = ['between', [$beginToday, $endToday]];
                $where['order_status'] = ['in', '20,30,40,50'];
                break;
            case 3:
                $where['order_status'] = 30;
                break;
            case 4:
                $where['order_status'] = 40;
                break;
            case 5:
                $where['order_status'] = 50;
                break;
            case 6:
                $where['order_status'] = 70;
                break;
            default:
                $where['order_status'] = ['in', '0,20,30,40,50,60,70'];
                break;
        }
        return $where;
    }

    //修改订单状态
    //订单状态:0=取消,10=待付款,20=待确认,21=已拒绝,30=待服务,40=服务中,50=已完成,60=已退款,70=质保中
    public function changeOrderStatus($id, $status)
    {

        $orderInfo = $this->where('id', $id)->find();
        if (!$orderInfo) {
            return ['status' => false, "data" => [], 'msg' => '订单不存在'];
        }

        //订单取消判断
        if ($status == 'cancel' && $orderInfo['cancel_status'] == '20') {
            return ['status' => false, "data" => [], 'msg' => '订单已被取消'];
        }
        if ($status == 'cancel' && $orderInfo['order_status'] == '40') {
            return ['status' => false, "data" => [], 'msg' => '订单状态错误'];
        }
        if ($status == 'cancel' && $orderInfo['order_status'] == '50') {
            return ['status' => false, "data" => [], 'msg' => '订单状态错误'];
        }
        if ($status == 'cancel' && $orderInfo['order_status'] == '60') {
            return ['status' => false, "data" => [], 'msg' => '订单状态错误'];
        }
        //订单付款判断
        if ($status == 'payed' && $orderInfo['pay_status'] == '20') {
            return ['status' => false, "data" => [], 'msg' => '订单已支付'];
        }
        if ($status == 'payedall' && $orderInfo['pay_status'] == '20') {
            return ['status' => false, "data" => [], 'msg' => '订单已支付'];
        }
        //订单确认判断
        if ($status == 'confirm' && $orderInfo['order_status'] != '20') {
            return ['status' => false, "data" => [], 'msg' => '订单状态错误'];
        }
        //订单拒绝判断
        if ($status == 'refuse' && $orderInfo['order_status'] != '20') {
            return ['status' => false, "data" => [], 'msg' => '订单状态错误'];
        }
        //订单公示
        if ($status == 'open' && $orderInfo['order_status'] > 21) {
            return ['status' => false, "data" => [], 'msg' => '订单状态错误'];
        }

        //订单议价判断
        if ($status == 'bargainpay' && $orderInfo['order_status'] != '30') {
            return ['status' => false, "data" => [], 'msg' => '订单状态错误'];
        }
        if ($status == 'bargainpay' && $orderInfo['pay_status'] == '20') {
            return ['status' => false, "data" => [], 'msg' => '订单已支付'];
        }
        if ($status == 'bargainpay-visit' && $orderInfo['visit_pay_status'] == '1') {
            return ['status' => false, "data" => [], 'msg' => '上门费已支付'];
        }
        //订单服务判断
        if ($status == 'service' && $orderInfo['order_status'] != '30') {
            return ['status' => false, "data" => [], 'msg' => '订单状态错误'];
        }

        //订单完工判断
        if ($status == 'checkorder' && $orderInfo['check_status'] != '10' && $orderInfo['check_status'] != '40') {
            return ['status' => false, "data" => [], 'msg' => '订单状态错误'];
        }
        if ($status == 'checknoorder' && $orderInfo['check_status'] != '20') {
            return ['status' => false, "data" => [], 'msg' => '订单状态错误'];
        }

        //订单质保判断
        if ($status == 'quality' && $orderInfo['pay_status'] != '20') {
            return ['status' => false, "data" => [], 'msg' => '订单还未支付尾款'];
        }
        if ($status == 'quality' && $orderInfo['order_status'] != '40') {
            return ['status' => false, "data" => [], 'msg' => '订单状态错误'];
        }

        //订单完成判断
//        if ($status == 'finished' && $orderInfo['pay_status'] != '20') {
//            return ['status' => false, "data" => [], 'msg' => '订单还未支付尾款'];
//        }
//        if ($status == 'finished' && $orderInfo['order_status'] != '40') {
//            return ['status' => false, "data" => [], 'msg' => '订单状态错误'];
//        }
        if ($status == 'finished' && $orderInfo['order_status'] != '70') {
            return ['status' => false, "data" => [], 'msg' => '订单状态错误'];
        }

        //订单评价判断
        // if ($status == 'comment' && $orderInfo['order_status'] != '70' && $orderInfo['order_status'] != '20') {
        //     return ['status' => false, "data" => [], 'msg' => '订单状态错误'];
        // }
        Db::startTrans();
        $nowTime = time();
        $date = date('Y-m-d', $nowTime);
        //消息模型
        $msgModel = new \app\common\model\xiservice\Message;
        $orderSaveData = [];
        try {
            switch ($status) {
                case 'cancel'://取消订单
                    $orderSaveData['order_status'] = '0';
                    $orderSaveData['cancel_status'] = '20';
                    $orderSaveData['cancel_time'] = $nowTime;
                    //服务销量-1     
                    $service = Service::where('id', $orderInfo['service_id'])->setDec('salenums');
                    //服务人员时间表调整
                    if ($orderInfo['worker_id'] > 0) {
                        $rev = ScheduleModel::where('order_id', $orderInfo['id'])->delete();
                        //取消通知
                        // $req = $msgModel->sendOrderMessage($orderInfo, 2);
                    }
                    //退款处理
                    if ($orderInfo['transaction_id']) {
                        $orderInfo['action']='cancel';
                        $ret = $this->wxrefund($orderInfo);
                    }
                    break;
                case 'payed'://付款 (固定价格)
                    $orderSaveData['order_status'] = '20';
                    $orderSaveData['pay_status'] = '20';
                    $orderSaveData['pay_time'] = $nowTime;
                    $orderSaveData['visit_pay_status'] = 1;
                    $orderSaveData['task_mode'] = 0;
                    //服务销量+1
                    $service = Service::where('id', $orderInfo['service_id'])->setInc('salenums');
                    //消息通知
                    if ($orderInfo['worker_id'] > 0) {
                        //下单通知
                        $req = $msgModel->sendOrderMessage($orderInfo, 1);
                    }
                    break;
                case 'payedall'://付款 (非固定价格)
                    $orderSaveData['order_status'] = '20';
                    $orderSaveData['pay_status'] = '10';
                    $orderSaveData['visit_pay_status'] = 0;
                    $orderSaveData['task_mode'] = 0;
                    //服务销量+1    
                    $service = Service::where('id', $orderInfo['service_id'])->setInc('salenums');
                    //消息通知
                    if ($orderInfo['worker_id'] > 0) {
                        //下单通知
                        $req = $msgModel->sendOrderMessage($orderInfo, 8);
                    }
                    break;
                case 'confirm'://服务人员确认订单
                    $orderSaveData['order_status'] = '30';
                    $orderSaveData['confirm_status'] = '20';
                    $orderSaveData['confirm_time'] = $nowTime;
                    //消息通知
                    if ($orderInfo['worker_id'] > 0) {
                        //更新服务人员时间表
                        $scheduleModel = new \app\common\model\xiservice\Schedule;
                        $req = $scheduleModel->orderSchedule($orderInfo['worker_id'], $orderInfo['id'], $orderInfo['service_start_time'], $orderInfo['service_duration']);
                        //已接单通知
                        $req = $msgModel->sendOrderMessage($orderInfo, 4);
                    }
                    break;
                case 'refuse': //服务人员拒绝订单
                    $orderSaveData['order_status'] = '21';
                    if ($orderInfo['transaction_id']) {
                        $orderInfo['action']='refuse';
                        $ret = $this->wxrefund($orderInfo);
                    }
                    break;
                case 'open': //订单公示
                    $orderSaveData['order_status'] = '20';
                    $orderSaveData['worker_id'] = 0;
                    $orderSaveData['task_mode'] = 0;
                    break;
                case 'bargainpay-visit'://议价上门费
                    $orderSaveData['visit_pay_status'] = 1;
                    $orderSaveData['pay_time'] = $nowTime;
                    $orderSaveData['order_status'] = '20';
                    break;
                case 'bargainpay'://议价结算 (非固定价格)
                    $orderSaveData['pay_status'] = '20';
                    $orderSaveData['pay_time'] = $nowTime;
                    $orderSaveData['visit_pay_status'] = 1;
                    break;
                case 'service'://订单状态流转
                    $orderSaveData['order_status'] = '40';
                    $orderSaveData['service_status'] = '20';
                    $orderSaveData['service_time'] = $nowTime;

                    //需要合同的生成合同
                    $this->mkContract($orderInfo);
                    break;
                case 'checkorder'://申请完工验收
                    $orderSaveData['check_status'] = '20';
                    $orderSaveData['check_time'] = time();

                    break;
                case 'checknoorder'://完工验收不通过
                    $orderSaveData['service_check_images'] = '';
                    $orderSaveData['service_check_remark'] = '';
                    $orderSaveData['check_status'] = '40';
                    $orderSaveData['check_time'] = null;

                    break;
                case 'quality'://订单进入质保
                    $orderSaveData['order_status'] = '70';
                    $orderSaveData['check_status'] = '30';
                    $orderSaveData['check_time'] = time();

                    $quality_days = $orderInfo->service->quality_day;
                    if ($quality_days) {
                        $orderSaveData['quality_end_time'] = time() + $quality_days * 86400;//质保到期时间
                    } else {
                        $orderSaveData['quality_end_time'] = time();
                    }

                    //结算收益
                    // $rbenfit = $this->settle($orderInfo, $orderSaveData['quality_end_time']);
                    break;
                case 'finished'://订单已完成
                    $orderSaveData['order_status'] = '50';
                    $orderSaveData['finish_time'] = $nowTime;
                    
                    break;
                case 'comment'://评价
                    $orderSaveData['order_status'] = '50';

                    $orderSaveData['comment_status'] = '20';
                    $orderSaveData['comment_time'] = $nowTime;
                    //消息通知
                    if ($orderInfo['worker_id'] > 0) {
                        //评价通知
                        // $req = $msgModel->sendOrderMessage($orderInfo, 3);
                    }
                    //更新评价分数
                    $allscore = CommentModel::where('staff_id', $orderInfo['worker_id'])->sum('rate');
                    $allnum = CommentModel::where('staff_id', $orderInfo['worker_id'])->count();
                    $rate = ($allscore + 5) / ($allnum + 1);
                    $ratedata['review'] = round($rate, 1);
                    $worker = XiserviceUser::where("user_id", $orderInfo['worker_id'])->update($ratedata);
                    //结算收益
                    $rbenfit = $this->settle($orderInfo,$nowTime);
                    break;
                 case 'diagnose'://评价
                    //结算收益
                    $msgModel->sendOrderMessage($orderInfo, 11);
                    $rbenfit = $this->settle2($orderInfo,$nowTime);
                    break;
                case 'refund'://退款
                    $orderSaveData['order_status'] = '60';
                    $orderSaveData['refund_status'] = '20';
                    $orderSaveData['refund_time'] = $nowTime;
                    //服务销量-1     
                    $service = Service::where('id', $orderInfo['service_id'])->setDec('salenums');
                    //退款处理
                    if ($orderInfo['transaction_id']) {
                        $ret = $this->wxrefund($orderInfo);
                    }
                    break;
                default:
                    break;
            }

            //更新状态
            $resv = $this->save($orderSaveData, ["id" => $id]);

            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            return ["status" => false, "data" => [], "msg" => $e->getMessage()];
        } catch (\InvalidArgumentException $e) {
            Db::rollback();
            return ["status" => false, "data" => [], "msg" => $e->getMessage()];
        }

        //待修改订单后发微信消息的
        $orderInfo = $this->where('id', $id)->find();
        if($status == 'checkorder') {
            //申请验收提醒通知
            $req = $msgModel->sendOrderMessage($orderInfo, 6);
        } else if($status == 'checknoorder' || $status == 'quality') {
            //验收结果通知提醒
            $req = $msgModel->sendOrderMessage($orderInfo, 7);
        }

        return ["status" => true, "data" => [], "msg" => "操作成功"];
    }

    //订单收益记录
    public function settle($orderInfo, $expiretime)
    {
        //平台服务费
        // isset(config('xiservice.order')['auto_benfit']) ? $platformfee = config('xiservice.order')['auto_benfit'] : $platformfee = 0;
        
       
        //产品服务费
        $service = Service::where("id", $orderInfo['service_id'])->find();
        $servicefee = $service['commission'];

        $platformfee = $servicefee;
        $scale = 100;

        //业务推广上级
        // $pid = $orderInfo->user->parent_user_id;
        // if ($pid) {
        //     $saleUser = XiserviceUser::where("user_id", $pid)->where('group_id', 4)->find();
        //     //业务提成
        //     if ($saleUser && $service['sale_rate']) {
        //         //去除销售分成比例
        //         $scale = $scale - $service['sale_rate'];
        //         $dividendMoney = bcmul($orderInfo['pay_money'], ($service['sale_rate'] / 100), 2);

        //         //记录销售分成订单
        //         $dividendData = [
        //             'user_id' => $saleUser['user_id'],
        //             'order_type' => 'service',
        //             'dividend_type' => 'order',
        //             'source_order_no' => $orderInfo['order_no'],
        //             'total_amount' => $orderInfo['pay_money'],
        //             'divide_rate' => $service['sale_rate'],
        //             'divide_money' => $dividendMoney,
        //             'extra_data' => '',
        //         ];
        //         $did = Dividend::insertGetId($dividendData);

        //         //记录销售分成
        //         $benfitdata['type'] = 3;
        //         $benfitdata['user_id'] = $saleUser['user_id'];
        //         $benfitdata['order_id'] = $did;
        //         $benfitdata['scale'] = $service['sale_rate'] / 100;
        //         $benfitdata['money'] = $dividendMoney;
        //         $benfitdata['status'] = 2;
        //         $benfitdata['createtime'] = time();
        //         $benfitdata['updatetime'] = time();
        //         BenfitModel::insertGetId($benfitdata);
        //         XiserviceUser::where("user_id", $saleUser['user_id'])->setInc("total_money", $dividendMoney);
        //         XiserviceUser::where("user_id", $saleUser['user_id'])->setInc("can_money", $dividendMoney);
        //     }
        // }

        //去除平台分成比例
        // if ($servicefee == 0) {
        //     $scale = $scale - $platformfee;
        // } else {
        //     $scale = $scale - $servicefee;
        // }

        $scale = $scale - $platformfee;
        //去除质保金冻结比例
        // $scale = $scale - $service['quality_rate'];

        //冻结质保金
        // $qualityRate = $service['quality_rate'] / 100;
        // $qualityMoney = bcmul($orderInfo['pay_money'], $qualityRate, 2);
        // $benfitdata['type'] = 1;
        // $benfitdata['user_id'] = $orderInfo['worker_id'];
        // $benfitdata['order_id'] = $orderInfo['id'];
        // $benfitdata['scale'] = $qualityRate;
        // $benfitdata['money'] = $qualityMoney;
        // $benfitdata['status'] = 1;
        // $benfitdata['createtime'] = time();
        // $benfitdata['createtime'] = time();
        // $benfitdata['expiretime'] = $expiretime;//冻结到期时间
        // BenfitModel::insertGetId($benfitdata);
        // XiserviceUser::where("user_id", $orderInfo['worker_id'])->setInc("freeze_money", $qualityMoney);

        //服务订单直接到账收益
        $scale = $scale / 100;
        $benfitmoney = bcmul($orderInfo['pay_money'], $scale, 2);
        $benfitdata['type'] = 1;
        $benfitdata['user_id'] = $orderInfo['worker_id'];
        $benfitdata['order_id'] = $orderInfo['id'];
        $benfitdata['scale'] = $scale;
        $benfitdata['money'] = $benfitmoney;
        $benfitdata['status'] = 2;
        $benfitdata['createtime'] = time();
        $benfitdata['updatetime'] = time();
        BenfitModel::insertGetId($benfitdata);
        XiserviceUser::where("id", $benfitdata['user_id'])->setInc("total_money", $benfitmoney);
        XiserviceUser::where("id", $benfitdata['user_id'])->setInc("freeze_money", $benfitmoney);


        //服务人员服务次数up
        $worker = XiserviceUser::where("user_id", $orderInfo['worker_id'])->setInc("service_num");
        //服务人员升级逻辑
        // $workerinfo = XiserviceUser::where("user_id", $orderInfo['worker_id'])->find();

        // $orderNum = $this->where('worker_id', $orderInfo['worker_id'])->where('order_status', '50')->count();
        // if ($workerinfo['level'] == 1) {
        //     isset(config('xiservice.level')['level_two_num']) ? $needNum = config('xiservice.level')['level_two_num'] : $needNum = 100;
        //     if ($orderNum >= $needNum) {
        //         $levelup = XiserviceUser::where("user_id", $orderInfo['worker_id'])->update(['level' => 2]);
        //     }
        // } else if ($workerinfo['level'] == 2) {

        //     isset(config('xiservice.level')['level_three_num']) ? $needNum = config('xiservice.level')['level_three_num'] : $needNum = 500;
        //     if ($orderNum >= $needNum) {
        //         $levelup = XiserviceUser::where("user_id", $orderInfo['worker_id'])->update(['level' => 3]);
        //     }
        // } else {
        //     //最高级不做任何处理
        // }
    }
    public function settle2($orderInfo, $expiretime)
    {
        $platformfee = 15;
        $scale = 100;

        $scale = $scale - $platformfee;
        //服务订单直接到账收益
        $scale = $scale / 100;
        $benfitmoney = bcmul($orderInfo['pay_money'], $scale, 2);
        $benfitdata['type'] = 1;
        $benfitdata['user_id'] = $orderInfo['worker_id'];
        $benfitdata['order_id'] = $orderInfo['id'];
        $benfitdata['scale'] = $scale;
        $benfitdata['money'] = $benfitmoney;
        $benfitdata['status'] = 2;
        $benfitdata['createtime'] = time();
        $benfitdata['updatetime'] = time();
        BenfitModel::insertGetId($benfitdata);
        XiserviceUser::where("id", $benfitdata['user_id'])->setInc("total_money", $benfitmoney);
        XiserviceUser::where("id", $benfitdata['user_id'])->setInc("freeze_money", $benfitmoney);


    }
    //微信商户号退款
    public function wxrefund($order)
    {
        $wx = new WeixinMini();
        $total = $order['pay_money'] * 100;
        
        if($order['action']=='cancel')
        {
            $time = time();
            $c = $time - $order['pay_time'];
            if($c > 7200) {
                $refund = $order['pay_money'] * 100 * 0.8;
            } else if($c > 3600){
                $refund = $order['pay_money'] * 100 * 0.8;
            } else if($c > 600){
                $refund = $order['pay_money'] * 100 * 0.8;
            } else {
                $refund = $order['pay_money'] * 100; 
            }
        }
        else
        {
            $refund = $order['pay_money'] * 100; 
        }          
        $refund_desc = '订单取消退款';
        $ret = $wx->refund('', $order['transaction_id'], $order['order_no'] . "_1", $total, $refund, $refund_desc);
    
        return $ret;
    }
    public function wxrefundone($transaction_id,$order_no,$total)

    {   $wx = new WeixinMini();
        $ret = $wx->refund('',$transaction_id, $order_no . "_1", $total, $total, '入驻被拒退款');
        return $ret;
    }

    /**
     * 生成合同
     */
    public function mkContract($orderInfo)
    {
        if ($orderInfo['have_contract']) {
            //找到模板
            $contract = Contract::where('service_id', $orderInfo['service_id'])
                ->find();

            $string = '甲方: ' . $orderInfo->worker->nickname . '; <br>';
            $string .= '乙方: ' . $orderInfo->user->nickname . '; <br>';
            $content = $string . $contract['content'];

            $string = '需求说明: ' . $orderInfo['service_desc'] . '; <br>';
            $string .= '服务地址: ' . $orderInfo['addr'] . $orderInfo['addr_detail'] . '; <br>';
            $string .= '上门费用: ' . $orderInfo['visit_money'] . '; <br>';
            $string .= '服务费用: ' . $orderInfo['service_money'] . '; <br>';
            $string .= '费用合计: ' . $orderInfo['total_money'] . '; <br>';

            $content = str_replace('{_content_}', $string, $content);

            OrderContact::create([
                'order_id' => $orderInfo['id'],
                'order_no' => $orderInfo['order_no'],
                'user_id' => $orderInfo['user_id'],
                'worker_id' => $orderInfo['worker_id'],
                'name' => $contract['name'],
                'content' => $content,
                'status' => 1,
            ]);
        }
    }
}
